<!-- 群发资源 -->
<template>
  <div> <!-- class="dashboard-editor-container" -->
    <el-row style="background: #fff; padding: 16px 16px; margin-bottom: 32px">
      <div style="display:flex;justify-content:space-between;">
        <!-- <div class="title">群发资源</div> -->
        <div >
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加资源</el-button>
        </div>
      </div>
        <!-- <div class="btn">
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加任务</el-button>
        </div> -->
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="资源名称" prop="Descp" align="left" width="220px"></el-table-column>
          <el-table-column label="创建时间" prop="CreateTime" align="left" width="220px"></el-table-column>
          <el-table-column label="创建人员" prop="EmployeeName" align="left" width="220px"></el-table-column>
          <el-table-column label="ResID" show-overflow-tooltip prop="ResID" align="left"></el-table-column>
          <!-- <el-table-column label="链接地址" prop="URL" align="left" show-overflow-tooltip></el-table-column> -->
          <el-table-column label="操作" align="left" width="160px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="checkMailGlobal(scope.row)">查看</el-button>
              <!-- <el-button size="mini" type="success" @click="changeMailGlobal(scope.row)">修改</el-button> -->
              <el-button size="mini" type="danger" @click="deleteMailGlobal(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
    </el-row>
    <el-dialog title="查看图片" :close-on-click-modal="false" :close-on-press-escape=false :visible.sync="imgdialog" v-el-drag-dialog width="50%">
      <el-image :src="'data:image/png;base64,' + imgurl" alt=""></el-image>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="imgdialog = false;">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      :title="Action === 1 ? '添加资源' : '修改资源' "
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="30%">
      <el-form label-width="100px" :model="resourceForm" :rules="rules" ref="resourceForm">
        <el-form-item label='附件:'>
          <el-upload
            class="upload-demo"
            action="#"
            multiple
            accept=".jpg,.png,.gif"
            ref="upload"
            :disabled="Action !== 1"
            :on-change="filechange"
            :http-request="uploadFile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label='资源名称:' prop="Descp">
          <el-input v-model="resourceForm.Descp" maxlength="16"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { connrequest } from '@/api/firstPage'
import { parseTime, getuuid } from '@/utils/index.js';
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
directives: { elDragDialog },
data() {
  return {
    pageNum: 1,
    pageSize: 10,
    total: 10,
    fileList: [],
    tableData: [],
    emailForm: {},
    emailList: [],
    imgurl:'',
    ImgBase64: '',
    imgdialog: false,
    dialogVisible: false,
    rules: {
      Descp:[
        { required: true, message: "请输入资源名称"}
      ]
    },
    resourceForm: {},
    Action: 1,
  }
},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    addResources(){
      this.Action = 1
      this.resourceForm = {}
      this.$nextTick(() => {
        this.$refs['resourceForm'].clearValidate()
        this.fileList = []
      })
      this.dialogVisible = true
    },
    changeMailGlobal(row){
      this.Action = 2
      this.resourceForm = {...row}
      this.dialogVisible = true
    },
    deleteMailGlobal(row){
      this.Action = 3
      this.resourceForm = {...row}
      this.$confirm('此操作将删除该资源, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              ...this.resourceForm
            }
          }
        }
        const res = await connrequest('EditEMailRes', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async getData() {
      const res = await connrequest('GetEMailResList')
      res.Data = res.Data || []
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
        return item
      })
      this.tableData = res.Data
    },
    submit(){
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          if(this.ImgBase64 === ''){
            this.$message.error('请先上传图片')
            return false
          }
          const data = {
            Data:{
              Action: this.Action,
              Detail: {
                ResID: '',
                Descp: this.resourceForm.Descp,
                URL: '',
                CreateTime:0,
              },
              ImgBase64: this.ImgBase64
            }
          }
          const res = await connrequest('EditEMailRes', data)
          if(res.Status.StatusCode === 0){
            this.Action === 1 ? this.$message.success('添加成功') : this.$message.success('修改成功')
            this.dialogVisible = false
            this.getData()
          }
        }
      })
    },
    async checkMailGlobal(row){
      const data = {
        Data:{
          ResID: row.ResID
        }
      }
      const res = await connrequest('GetEMailResDetail', data)
      this.imgdialog = true
      this.imgurl = res.Data.ImgBase64
    },
    filechange(file){
      if (!/\.(jpg|jpeg|png|GIF|JPG|PNG|gif)$/.test(file.name) ) { 
        this.$message.error('请选择png/jpg/gif格式的文件')
        this.$refs['resourceForm'].clearValidate()
        this.fileList = []
        return false
      }
      else if(file.size > 512000){
        this.$message.error('请选择小于512k的图片')
        this.$refs['resourceForm'].clearValidate()
        this.fileList = []
        return false
      }
      let that = this
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e)
      {
        that.ImgBase64 = this.result.split(',')[1]
      }
    },
    uploadFile(){},
    async handleRemove(file, fileList) {
      const data = {
        Data:{
          InnerName: file.uid
        }
      }
      const res = await connrequest('DeleteEMailAttach', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('文件删除成功')
        this.ImgBase64 = ''
      }
    },
    async handlePreview(file) {
      // const data = {
      //   Data:{
      //     FileName: file.InnerName
      //   }
      // }
      // const res = await downloadfile('DownloadPublicFile', data)
      // let blobUrl = window.URL.createObjectURL(new Blob([res]));
      // const a = document.createElement('a');
      // a.style.display = 'none';
      // a.download = file.InnerName;
      // a.href = blobUrl;
      // a.click();
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
.content {
  position: relative;
  margin-top: 25px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  ::v-deep .certification{
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
  margin-bottom: 20px;
}
.btn{
  margin: 20px 0;
}

</style>